/*
 * @Description: xxx描述文件内容
 * @Autor: gufuyan
 * @Date: 2021-11-24 09:05:53
 * @lastModifiedBy: gufuyan
 * @LastEditTime: 2021-11-29 19:34:35
 * @lastModifiedContent: xxx描述修改的内容
 */
import React, { useCallback } from 'react';
import { LogoutOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin } from 'antd';
import { history, useModel } from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import type { MenuInfo } from 'rc-menu/lib/interface';

export type GlobalHeaderRightProps = {
  menu?: boolean;
};

const loginOut = () => {
  function setCookie(cname: string, cvalue: string, exdays: number) {
    const d = new Date();
    const { domain } = document;
    d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
    const expires: string = `expires=${d.toUTCString()}`;
    if (domain === 'my-beta.chinasie.com') {
      document.cookie = `${cname}=${cvalue}; ${expires};domain=chinasie.com; path=/`;
    } else {
      document.cookie = `${cname}=${cvalue}; ${expires};domain=${domain}; path=/`;
    }
  }
  setCookie('token', '', -1);
  // window.location.href = `${URL_PRE}/${DEFINE_CONTEXT}`;
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout' && initialState) {
        setInitialState({ ...initialState, currentUser: undefined });
        loginOut();
        return;
      }
      history.push(`/account/${key}`);
    },
    [initialState, setInitialState],
  );

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { userInfo } = initialState;

  if (!userInfo || !userInfo?.userId) {
    return loading;
  }

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );
  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar src={userInfo?.userImage} />
        <div className={styles.userInfo}>
          <div className={styles.userName}>{userInfo?.zhName}</div>
          {/* <div className={styles.dept}>{`${userInfo?.orgName || ''} / ${
            userInfo?.position || ''
          } / ${userInfo?.rank || ''}`}</div> */}
        </div>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
